import {Button, CssVarsProvider, Divider, IconButton, Textarea} from "@mui/joy";
import {useEffect, useState} from "react"
import "./style.css";
import React from "react/index";
import uuidWrapper from "~utils/uuid";
import Icon from "~utils/icon";
import remove from "~api/highlightText/remove";
import getShortcutByName from "~storage/slash/api/getShortcutByName";
import {decodeURIWrapper} from "~utils/common";

async function getFromBackgroundPage(payload, ignoreErrors = true) {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage(payload, (response) => {
      const error = chrome.runtime.lastError;
      if (!ignoreErrors && error) {
        reject(error);
        return;
      }

      if (!ignoreErrors && response.success === false) {
        reject(response.error);
        return;
      }

      resolve(response.response);
    });
  });
}

const IndexPopup = () => {
  const [highlightPage, setHighlightPage] = useState({
    highlightId: "",
    highlightComments: "",
    viewstate: ""
  });
  const [highlightList, setHighlightList] = useState([]);
  const [lostHighlightList, setLostHighlightList] = useState([]);

  useEffect(() => {
    getFromBackgroundPage({ action: 'get-highlights' }, false)
      .then((highlights) => {
        console.log(`get-highlights: ${JSON.stringify(highlights)}`);
        const tempHighlightList = [];
        let tempHighlightPage = { ...highlightPage };
        for (const highlight of highlights){
          const highlightId = highlight[0];
          const [highlightText, viewstate] = highlight[1].split(";_;");
          const [highlightComments] = viewstate.split(";;").slice(-1);
          if (viewstate.indexOf("*ver_page*") !== -1){
            tempHighlightPage.highlightId = highlightId;
            tempHighlightPage.highlightComments = highlightComments;
            tempHighlightPage.viewstate = viewstate;
            console.log(`clonedHighlightPage: ${JSON.stringify(tempHighlightPage)}`);
          } else {
            tempHighlightList.push({
              highlightId: highlightId,
              highlightText: highlightText,
              highlightComments: highlightComments,
              viewstate: viewstate
            })
            // document.getElementById(highlightId).addEventListener('click', () => {
            //   chrome.runtime.sendMessage({ action: 'show-highlight', highlightId });
            // });
          }
        }
        setHighlightList(tempHighlightList);
        setHighlightPage(tempHighlightPage);

        /* get-highlights的返回值参考
        ef97031e-bbe6-4b59-9c20-3456c34b6d13,占领加沙;_;ef97031e-bbe6-4b59-9c20-3456c34b6d13;;%23root%3Ediv%3Anth-of-type%281%29%3Emain%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%283%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%282%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%282%29%3Espan%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Espan%3Anth-of-type%281%29%3Ep%3Anth-of-type%283%29;;%5FRC%5F%3EtextNode%3Anth-of-type%280%29;;%5FRC%5F%3EtextNode%3Anth-of-type%280%29;;161;;165;;%E5%8D%A0%E9%A2%86%E5%8A%A0%E6%B2%99;;rgb%28255%2C%20246%2C%2021%29;;4.0.0;;,891f3479-8b9a-48b9-89c3-bf12dbccc8e4,古老文明;_;891f3479-8b9a-48b9-89c3-bf12dbccc8e4;;%23root%3Ediv%3Anth-of-type%281%29%3Emain%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%283%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%282%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%282%29%3Espan%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Ediv%3Anth-of-type%281%29%3Espan%3Anth-of-type%281%29%3Ep%3Anth-of-type%284%29;;%5FRC%5F%3EtextNode%3Anth-of-type%280%29;;%5FRC%5F%3EtextNode%3Anth-of-type%280%29;;40;;44;;%E5%8F%A4%E8%80%81%E6%96%87%E6%98%8E;;rgb%28255%2C%20246%2C%2021%29;;4.0.0;;
        1. 首先是用逗号","分隔数组元素。数组元素为highlightId,highlight。注意，如果是多条高亮，也是用逗号","分隔。因此如果是两个高亮元素，则用逗号会分成4份
        2. 用";_;"来分隔高亮文本(highlightText)和viewstate
        3. viewstate内部则用";;"来分隔
         */
      });
    getFromBackgroundPage({ action: 'get-lost-highlights' })
      .then((lostHighlights) => {
        console.log(`get-lost-highlights: ${JSON.stringify(lostHighlights)}`);
        const tempHighlightLostList = [];
        for (const lostHighlight of lostHighlights){
          console.log(`lostHighlight: ${JSON.stringify(lostHighlight)}`);
          // const highlightId = lostHighlight.index;
          // const [highlightText, viewstate] = lostHighlight[1].split(";_;");
          // const [highlightComments] = viewstate.split(";;").slice(-1);
          tempHighlightLostList.push({
            highlightId: lostHighlight.index,
            highlightText: lostHighlight.highlightText,
            highlightComments: lostHighlight.highlightComments,
          });
        }
        setLostHighlightList(tempHighlightLostList);
      });
  }, []);

  useEffect(() => {
    for (const highlight of highlightList){
      const highlightId = highlight.highlightId;
      const divvv = document.getElementById(highlightId);
      divvv.addEventListener('click', () => {
        console.log(`sending click... ${highlightId}`);
          chrome.runtime.sendMessage({ action: 'show-highlight', highlightId });
        });
      console.log(`divvv: ${divvv.innerText}`);
    }

// document.getElementById(highlightId).addEventListener('click', () => {
    //   chrome.runtime.sendMessage({ action: 'show-highlight', highlightId });
    // });
  }, [highlightList]);

  const handlePageCommentsChange = async (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    console.log("inside handlePageCommentsChange");
    const comments = e.target.value;
    let highlightId = uuidWrapper();
    let viewstate = "";
    if (e.target.parentNode.getAttribute("highlightId")){
      // update
      highlightId = e.target.parentNode.getAttribute("highlightId");
      viewstate = e.target.parentNode.getAttribute("viewstate");
      chrome.runtime.sendMessage({ action: 'update-comments', highlightId: highlightId, viewstate: viewstate, comments: comments });
    } else {
      // create
      console.log("inside create")
      const currentColor = await getFromBackgroundPage({ action: 'get-current-color' }, false);
      console.log(`currentColor: ${currentColor}`);
      const newPageComments = await getFromBackgroundPage({ action: 'create-page-comments', color: currentColor, comments: comments }, false);
      console.log(`newPageComments: ${newPageComments}`);
    }
    const updatedHighlightPage = { ...highlightPage, highlightComments: comments };
    setHighlightPage(updatedHighlightPage);
  };
  const handleCommentsChange = async (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const comments = e.target.value;
    const viewstate = e.target.parentNode.getAttribute("viewstate");
    const highlightId = viewstate.split(";;")[0];
    chrome.runtime.sendMessage({ action: 'update-comments', highlightId: highlightId, viewstate: viewstate, comments: comments });
    const updatedHighlightList = highlightList.map((highlight) => {
      if (highlight.highlightId === highlightId) {
        return { ...highlight, highlightComments: comments };
      }
      return highlight;
    });
    setHighlightList(updatedHighlightList);
    console.log(`update comments: ${comments}, highlightId: ${highlightId}, viewstate: ${viewstate}`);
  };
  const handleSaveClick = async (e) => {
    console.log(`handle save...`);
    const url = location.hostname + location.pathname;
    const shortcut = await getShortcutByName("59c980a3517fccd7053c3240c39bcf5e3df78f7f");
    console.log(JSON.stringify(shortcut));
    // const highlightId = currentHighlightElem.getAttribute('data-highlight-id');
    // const viewstate = currentHighlightElem.getAttribute("viewstate");
    // console.log(`highlightId: ${highlightId}`);
    // console.log(`viewstate: ${viewstate}`);
    // remove(highlightId, viewstate);
  };
  return (
    <div className="flex flex-col justify-start w-[560px]">
      <div id="title-setcion" className="flex flex-row flex-shrink-0 m-[22] cursor-default">
        <h1 className="text-[40px] font-bold">Highlighter</h1>
      </div>
      <div id="highlights-section">
        <div id="page-comments">
          <Textarea
            minRows="3"
            maxRows="6"
            value={highlightPage.highlightComments}
            onChange={handlePageCommentsChange}
            viewstate={highlightPage.viewstate}
          />
        </div>
        <div id="tools" className="flex flex-row justify-end">
          <IconButton size="sm" style={{margin: "2px 4px 2px 0px"}} title='Copy'>
            <Icon.CopyIcon/>
          </IconButton>
          <IconButton size="sm" style={{margin: "2px 4px 2px 0px"}} title='Save' onClick={handleSaveClick}>
            <Icon.SaveAllIcon/>
          </IconButton>
        </div>
        <Divider className="!my-2"/>
        <div id="highlights-list" className="flex flex-col">
          {
            highlightList.map((highlight) => { return (
              <div id={highlight.highlightId} key={highlight.highlightId}>
                <div className="flex flex-row justify-between">
                  <div>{highlight.highlightText}</div>
                  <Button size="sm" style={{margin: "2px 2px 4px 0px"}}>Copy</Button>
                </div>
                <Textarea
                  minRows="3"
                  maxRows="6"
                  value={decodeURIWrapper(highlight.highlightComments)}
                  onChange={handleCommentsChange}
                  viewstate={highlight.viewstate}
                />
              </div>
            );
            })
          }
        </div>
        <div id="highlights-lost-list" className="flex flex-col">
          {
            lostHighlightList.map((highlight) => { return (
              <div id={highlight.highlightId} key={highlight.highlightId}>
                <div className="flex flex-row justify-between"
                >
                  <div>{highlight.highlightText}</div>
                  <span>Delete</span>
                </div>
                <div>{highlight.highlightComments}</div>
              </div>
            );
            })
          }
        </div>
      </div>
    </div>
  )
}

const Popup = () => {
  return (
    <CssVarsProvider>
      <IndexPopup />
    </CssVarsProvider>
  );
}
export default Popup
